﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio;
using Minio.DataModel;
using Minio.DataModel.Args;
using Newtonsoft.Json;

namespace I_FileUpload.Controllers
{
    /// <summary>
    /// 文件管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly IMinioClient minioClient;
        private string BucketName = "sheepimages";

        public FileController()
        {
        
            minioClient = new MinioClient()
                .WithEndpoint("127.0.0.1:9005")
                //MinI0 服务器的端点地址为"10.31.60.18:9000"
                .WithCredentials("admin","admin123")  //MinIO 服务器连接所需的凭据，包括用户名和密码
                .WithSSL(false)                        //MinIO 服务器是否启用SSL加密通信
                .Build();                              //MinIO 服务器配置完成，构建MinioClient实例
        }


        /// <summary>
        /// 列出所有桶
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ListBuckets()
        {

            try
            {

                // 验证连接
                
                var buckets = await minioClient.ListBucketsAsync().ConfigureAwait(false);          
                return buckets != null ? Ok(buckets) : NotFound();
            }
            catch (Exception ex)
            {
                // 记录异常日志
               
                return StatusCode(500, "获取存储桶列表失败");
            }
            
        }


        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            
            //检查桶是否存在
            var beArgs = new BucketExistsArgs().WithBucket(BucketName);
            bool found = await minioClient.BucketExistsAsync(beArgs);

            //如果不存在 创建桶
            if(!found)
            {
                var mbArgs= new MakeBucketArgs().WithBucket(BucketName);
                await minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);  
            }

            var objectName = file.FileName;


            var putArgs= new PutObjectArgs()
                             .WithBucket(BucketName)
                             .WithObject(objectName)
                             .WithStreamData(file.OpenReadStream())
                             .WithContentType(file.ContentType)
                             .WithObjectSize(file.Length);
            await minioClient.PutObjectAsync(putArgs).ConfigureAwait(false);

            var getArgs = new PresignedGetObjectArgs()
                .WithBucket(BucketName)
                .WithObject(objectName)
                .WithExpiry(7200);
            var url=await minioClient.PresignedGetObjectAsync(getArgs).ConfigureAwait(false);

            return Ok(url);
        }

        [HttpPost]
        public async Task<IActionResult> UploadFiles(IFormFileCollection formFiles)
        {
            //检查桶是否存在
            var beArgs=new BucketExistsArgs().WithBucket(BucketName);
            bool found = await minioClient.BucketExistsAsync(beArgs);
            //如果不存在,则创建桶
            if(!found)
            {
                var mbArgs=new MakeBucketArgs().WithBucket(BucketName);
                await minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
            }

            var  fromFileList=new List<string>();
            foreach (var file in formFiles)
            {
                using var stream= file.OpenReadStream();
                var objectName = file.FileName;
                fromFileList.Add(objectName);


                //流数据上传
                var putArgs = new PutObjectArgs()
                    .WithBucket(BucketName)
                    .WithObject(objectName)
                    .WithStreamData(stream)
                    .WithContentType(file.ContentType)
                    .WithObjectSize(file.Length);

                await minioClient.PutObjectAsync(putArgs).ConfigureAwait(false);


                var getArgs = new PresignedGetObjectArgs()
                .WithBucket(BucketName)
                .WithObject(objectName)
                .WithExpiry(7200);
                var url = await minioClient.PresignedGetObjectAsync(getArgs).ConfigureAwait(false);
            }

            return Ok(JsonConvert.SerializeObject(fromFileList));
        }

        /// <summary>
        /// 根据对象名获取图片的预签名URL
        /// </summary>
        /// <param name="objectName">对象名</param>
        /// <returns>预签名URL</returns>
        [HttpGet]
        public async Task<IActionResult> GetImageUrl(string objectName)
        {
            var getArgs = new PresignedGetObjectArgs()
                .WithBucket(BucketName)
                .WithObject(objectName)
                .WithExpiry(7200); // 有效期2小时
            var url = await minioClient.PresignedGetObjectAsync(getArgs);
            return Ok(url);
        }







    }



}
